package kr.or.javacafe.member.controller;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import kr.or.common.util.FileUpDownUtil;
import kr.or.common.util.RoleUtil;
import kr.or.common.util.*;
import kr.or.javacafe.member.bo.*;
import kr.or.javacafe.member.domain.*;

@Controller
@RequestMapping("/member")
public class MemberController {
	
	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(MemberController.class);
		
	@Value("#{commonProp['member.thumbnail.path.local']}")
	String m_strLocalThumbnailPath; 

	@Value("#{commonProp['member.thumbnail.path.server']}")
	String m_strServerThumbnailPath; 
	
	String m_SEPARATOR = System.getProperty("file.separator");

	@Autowired
	MemberBO memberBO;

	
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "/member/login";
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout() {
		return "/member/logout";
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String addData(Model model) {
		model.addAttribute("user", new User());
		
		return "member/add";
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addData(@Valid User user, BindingResult result, SessionStatus status) {
		if (result.hasErrors()) {
			return "member/add";
		} 
		memberBO.addUser(user);
		status.setComplete();			

		return "redirect:/member/login";
	}

	@RequestMapping(value = "/edit/{userId}", method = RequestMethod.GET)
	public String editData(@PathVariable String userId, Model model) {
		User param = new User();
		param.setId(userId);
		
		model.addAttribute("user", memberBO.viewUser(param));
		
		return "member/edit";
	}

	@RequestMapping(value = "/edit/{userId}", method = RequestMethod.POST)
	public String editData(@PathVariable String userId, @Valid User user, BindingResult result, SessionStatus status) {
		if (result.hasErrors()) {
			return "member/edit";
		} 
		memberBO.editUser(user);
		status.setComplete();			

		return "redirect:/member/view/" + userId;
	}
	
	@RequestMapping(value = "/add/overlap/{userId}", method = RequestMethod.GET)
	@ResponseBody
	public String checkOverlap(@PathVariable String userId) {
		if (memberBO.isOverlapUser(userId))
			return "FAIL";
		else
			return "SUCCESS";
	}

	@RequestMapping(value = "/view/{userId}", method = RequestMethod.GET)
	public String view(@PathVariable String userId, Model model) {
		User param = new User();
		param.setId(userId);
		
		model.addAttribute("user", memberBO.viewUser(param));
		
		return "member/view";
	}
	
	@RequestMapping(value = "/hist", method = RequestMethod.GET)
	public String hist(Model model) {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String strId = ((UserDetails)principal).getUsername();

		model.addAttribute("userId", strId);
		
		return "member/userHistory";
	}
	

	@RequestMapping(value = "/hist/view", method = RequestMethod.GET)
	@ResponseBody
	public List<UserHistory> histView(Model model) {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String strId = ((UserDetails)principal).getUsername();

		UserHistory param = new UserHistory();
		param.setId(strId);
		
		return memberBO.getUserHistory(param);
	}
	
	@RequestMapping(value = "/hist/add", method = RequestMethod.POST)
	@ResponseBody
	public String histAdd(@RequestParam String contents) {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String strId = ((UserDetails)principal).getUsername();

		UserHistory param = new UserHistory();
		param.setId(strId);
		param.setHist(contents);
		
		memberBO.addUserHistory(param);
		
		return "SUCCESS";
	}	
	
	@RequestMapping(value = "/hist/remove/HIST_SEQ/{histSeq}", method = RequestMethod.GET)
	@ResponseBody
	public String histAdd(@PathVariable int histSeq) {
		UserHistory param = new UserHistory();
		param.setSeq(histSeq);
		
		memberBO.removeUserHistory(param);
		
		return "SUCCESS";
	}	
	

	@RequestMapping(value = "/thumbnail/check/USER_ID/{strId}", method = RequestMethod.GET)
	@ResponseBody
	public String thumbNailCheck(@PathVariable String strId, HttpServletResponse response) throws IOException {

		String strThumnailFullPath;		
		if (System.getProperty("os.name").contains("Windows")) {
			strThumnailFullPath = m_strLocalThumbnailPath;				
		} else {
			strThumnailFullPath = m_strServerThumbnailPath;							
		}

		int intSize = FileUpDownUtil.fileSize(strThumnailFullPath, strId + ".jpg");
		if (intSize == 0) {
			return "0";
		} else {
			return new Integer(intSize).toString(); 
		}
	}
	

	@RequestMapping(value = "/thumbnail/upload", method = RequestMethod.POST)
	//@ResponseBody 컴포넌트가 application/json 타입을 지원하지않으므로 text/html 타입으로 json을 리턴한다.
	public void thumbNailUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {

		// 사용자 정보
		User objUserInfo = RoleUtil.getUserInfo();
		if (objUserInfo == null) {
			response.getWriter().append("{success:false, fileSize:0}");
		}
		String strId = objUserInfo.getId();
		
		String strThumnailFullPath;		
		if (System.getProperty("os.name").contains("Windows")) {
			strThumnailFullPath = m_strLocalThumbnailPath;				
		} else {
			strThumnailFullPath = m_strServerThumbnailPath;							
		}

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
		MultipartFile mpFile = multipartRequest.getFile("attachFile");

		// 파일 사이즈 체크 (모두 허용 - web 단에서 체크함)		
		// 파일 확장자 체크 (모두 허용 - web 단에서 체크함)

		// 파일 이름을 사용자 아이디로 변경한다.
		String strUserIdFileName = strId + ".jpg"; 	// id.jpg

		long lngFileSize = mpFile.getSize();
		String strFileType = mpFile.getContentType();

		// 업로드
		int intRet = FileUpDownUtil.fileUpload(lngFileSize, mpFile.getInputStream(), strThumnailFullPath, strUserIdFileName);

		if (intRet == -1) {
			response.getWriter().append("{success:false, fileSize:" + lngFileSize + "}");
		} else if (intRet == -2) {
			response.getWriter().append("{success:false, fileSize:0}");
		} else {
			response.setContentType("text/html; charset=utf-8");
			response.getWriter().append("{success:true, tempFileName:'" + strUserIdFileName + "', fileSize:" + lngFileSize + ", contentType:'" + strFileType + "'}");
		}
	}

	
	@RequestMapping(value = "/thumbnail/download/EXT/{fileExt}/FILE/{fileNm}", method = RequestMethod.GET)
	public void thumbNailDownload(@PathVariable String fileExt, @PathVariable String fileNm, HttpServletResponse response) throws IOException {

		String strThumnailFullPath;		
		if (System.getProperty("os.name").contains("Windows")) {
			strThumnailFullPath = m_strLocalThumbnailPath;				
		} else {
			strThumnailFullPath = m_strServerThumbnailPath;							
		}
		
		int intSize = FileUpDownUtil.fileSize(strThumnailFullPath, fileNm + ".jpg");
		if (intSize == 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("IMG : " + strThumnailFullPath + " -> " + "no_user_image.jpg");
			}
			// 기본 이미지 다운로드
			FileUpDownUtil.imageDownload(response, strThumnailFullPath, "no_user_image.jpg");
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("IMG : " + strThumnailFullPath + " -> " + fileNm + ".jpg");
			}
			// 업로드 이미지 다운로드 
			FileUpDownUtil.imageDownload(response, strThumnailFullPath, fileNm + ".jpg");
		}
	}

	

}







